from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from app01 import models


class UserSer(serializers.Serializer):
    username = serializers.CharField(min_length=2, max_length=10,
                                     error_messages={
                                         'min_length': '用户名不能少于两个字符',
                                         'max_length': '用户名不可以长于十个字符·',
                                         'blank': ' 用户名不能为空'
                                     }
                                     )
    password = serializers.CharField(min_length=3, max_length=20,
                                     error_messages={
                                         'min_length': '密码不可短于3个字符',
                                         'max_length': '密码不可长于20个字符',
                                         'blank': '密码不能为空'
                                     }
                                     )
    phone = serializers.CharField(error_messages={'blank': '电话号码不能为空'})

    def create(self, validated_data):
        obj = models.Users.objects.create(**validated_data)
        return obj

    def validate_username(self, data):
        if models.Users.objects.filter(username=data):
            raise ValidationError('该用户名已存在')
        return data


class UserInfo(serializers.Serializer):
    username = serializers.CharField()
    phone = serializers.CharField()


class ParkingSpaceSer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    address = serializers.CharField(error_messages={'blank': '地址不能为空', 'required': '需要发送设备id'})
    device_id = serializers.CharField(error_messages={'blank': '设备号不能为空', 'required': '需要发送设备id'})
    longitude = serializers.CharField(error_messages={'blank': '地址不能为空', 'required': '需要发送设备id'})
    latitude = serializers.CharField(error_messages={'blank': '设备号不能为空', 'required': '需要发送设备id'})
    user = UserInfo(required=False)


class PeriodSer(serializers.Serializer):
    time_start = serializers.DateTimeField(error_messages={'required': '需要发送time_start键值对'})
    time_end = serializers.DateTimeField(error_messages={'required': '需要发送time_end键值对'})


class DeviceNameSer(serializers.Serializer):
    name = serializers.CharField()


class DeviceSer(serializers.Serializer):
    number = serializers.CharField()
    device = DeviceNameSer()
    is_use = serializers.BooleanField()


class OrdersSer(serializers.ModelSerializer):
    class Meta:
        model = models.Orders
        exclude = ['user', 'parking_space', 'code']


class OrderSer(serializers.Serializer):
    id = serializers.IntegerField()
    car = serializers.CharField()
    status = serializers.BooleanField()
    payment = serializers.DecimalField(max_digits=4, decimal_places=2)
    create_time = serializers.DateTimeField()
    start_time = serializers.DateTimeField()
    end_time = serializers.DateTimeField()
    user = UserInfo()
    parking_space = ParkingSpaceSer()